
package com.leenmvc.core.security.service.core;

import com.leenmvc.core.annotation.TransactionMulti;
import com.leenmvc.core.base.BaseService;
import com.leenmvc.core.dao.mysql.wrapper.QueryWrapper;
import com.leenmvc.core.exception.BusinessException;
import com.leenmvc.core.security.dao.core.SysDeptDao;
import com.leenmvc.core.security.entity.core.SysDept;
import com.leenmvc.core.security.entity.core.SysUser;
import com.leenmvc.core.utils.validator.ValidatorUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysDeptService extends BaseService<SysDept> {

    @Autowired
    private SysDeptDao sysDeptDao;

    @Autowired
    private SysUserService sysUserService;

//    @Autowired
//    private CarService carService;

    /**
     * 更新部门信息数据
     *
     * @param t
     */
    @Override
    public <T> boolean update(T t) {
        SysDept sysDept = (SysDept) t;
        Long pid = sysDept.getPid();
        Long id = sysDept.getId();
        ValidatorUtils.notNull("NOTNULL_FAIL", id, pid);
        if (id.toString().equals(pid.toString())) {
            throw new BusinessException("部门管理中修改不能将自己设为上级部门。");
        }
        if (!sysDeptDao.update(t)) {
            throw new BusinessException("INSERT_FAIL", SysDept.class);
        }
        return true;
    }

    /**
     * 添加一个部门信息记录
     *
     * @param t
     */
    @Override
    @TransactionMulti
    public <T> boolean insert(T t) {
        SysDept sysDept = (SysDept) t;
        Long pid = sysDept.getPid();
        //查询出上级部门的信息
        SysDept sysDept1 = sysDeptDao.get(pid);
        if (pid != 0) {
            //说明新增的为非顶级部门，pid=0为顶级部门
            String pids = findPids(sysDept, new StringBuilder());
            sysDept.setPids(pids);
//            String pds = sysDept1.getPids();
//            if (pds != null && !pds.equalsIgnoreCase("")) {
//                sysDept.setPids(pds);
//            } else {
//                sysDept.setPids(pid.toString());
//            }
        }
        if (!sysDeptDao.insert(sysDept)) {
            return false;
        }
//        sysDept.setId(null);
//        sysDeptDao.insert(sysDept);

        return true;
    }

    /**
     * 根据id删除部门信息数据
     */
    @TransactionMulti
    public void delById(Long id) {
        //判断是否有子部门
        List<Long> subList = listBySqlKey("getSubDeptIdList", "id", id);
        if (subList.size() > 1) {
            throw new BusinessException("该部门下面有子部门");
        }
        QueryWrapper wrapper = getQueryWrapper(SysUser.class);
        wrapper.eq("deptId", id);

        List<SysUser> sysUsers = sysUserService.query(wrapper);
        if (null != sysUsers && sysUsers.size() > 1) {
            throw new BusinessException("该部门有用户绑定,无法删除");
        }
        //子部门id所绑定用户
        for (Long childId : subList) {
            wrapper = getQueryWrapper(SysUser.class);
            wrapper.eq("deptId", childId);
            List<SysUser> list = sysUserService.query(wrapper);
            if (null != list && list.size() > 1) {
                throw new BusinessException("该部门下面子部门有用户绑定");
            }
        }
        if (!deleteById(id)) {
            throw new BusinessException("部门表信息删除失败！");
        }
    }

    public Long findTopId(SysDept dept) {
        if (null == dept) {
            return null;
        }
        SysDept parent = null;
        //如果上级Id不等于空
        Long pid = dept.getPid();
        if (pid == 0) {
            //自己就是顶级Id
            dept.setTopId(0L);
            return 0L;
        } else {
            //拿到父实体
            parent = findParent(dept);
            //如果父实体的父Id不为空
            if (null != parent && 0 == parent.getPid()) {
                dept.setTopId(parent.getId());
                return parent.getId();
            } else {
                return findTopId(parent);
            }
        }
    }

    /**
     * 拿到自己父级
     *
     * @param dept
     * @return
     */
    public SysDept findParent(SysDept dept) {
        List<SysDept> list = listBySqlKey("getById", "id", dept.getPid());
        if (0 == list.size()) {
            return null;
        }
        return list.get(0);
    }


    /**
     * 把部门的所有上级部门的Id用,拼接成字符串pids
     *
     * @param dept
     * @return
     */
    public String findPids(SysDept dept, StringBuilder pids) {
        if (null == pids) {
            pids = new StringBuilder();
        }
        if (null == dept) {
            return null;
        }
        SysDept parent = null;
        //如果上级Id不等于空
        Long pid = dept.getPid();
        if (pid == 0) {
            //自己就是顶级Id
            dept.setTopId(0L);
            pids.append(pid);
            return pids.toString();
        } else {
            //拿到父实体
            parent = findParent(dept);
            //如果父实体的父Id不为空
            if (null != parent && 0 == parent.getPid() && null == parent.getPids()) {
                dept.setTopId(parent.getId());
                pids.append(parent.getId());
                return pids.toString();
            } else {
                pids.append(parent.getId() + ",");
                return findPids(parent, pids);
            }
        }
    }

}
